<?php
// +----------------------------------------------------------------------
// | Azthink通用开发平台 [ TOMORROW IS ANOTHER DAY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 http://www.azthink.top All rights reserved.
// +----------------------------------------------------------------------
// | Author 李忠<ny_lizhong@126.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use app\common\model\Tree;
use think\Db;
use think\Model;

/**
 * 分类模型
 * @author 李忠<ny_lizhong@126.com>
 * @createAt 2018-09-19 17:16:29
 */
class Category extends Model {

    public static $TYPE_BLOG = 1;

    // 设置当前模型对应的完整数据表名称
    protected $table = '__SYS_CATEGORY__';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //数据自动完成
    protected $auto = ['update_by' => UID];
    protected $insert = ['create_by' => UID];

    //修改器
    public function getStatusTextAttr($value, $data) {
        return get_status_html($data['status']);
    }

    public function getTypeTextAttr($value, $data) {
        return get_config_text('category_type', $data['type']);
    }

    //自定义方法
    public static function lists($status, $type, $title, $pid = 0) {

        $map = array(['a.pid', '=', $pid]);
        if ($status !== null && $status !== '') {
            array_push($map, ['a.status', '=', $status]);
        } else {
            array_push($map, ['a.status', '>=', 0]);
        }
        if ($type !== '' && !empty($type)) {
            array_push($map, ['a.type', '=', $type]);
        }

        if ($title !== '' && !empty($title)) {
            array_push($map, ['a.title|a.name', 'like', '%' . $title . '%']);
        }
        return self::alias('a')->leftJoin('__SYS_CATEGORY__ b', 'a.pid = b.id')
            ->where($map)
            ->field('a.*, b.title as parent_title, (select count(1) from ' . self::getTable('sys_category') . ' c where c.pid = a.id and c.status>0) as child_count')
            ->order('a.sort, a.id desc')->paginate();
    }

    // 将分类转换为树
    public static function toFormatTree($type = 1) {
        $list = self::where(array(['status', '=', 1], ['type', '=', $type]))
            ->order('sort')->field('id,pid,title')->select();
        $treeModel = new Tree();
        $tree_list = $treeModel->toFormatTree($list->toArray());
        return $tree_list;
    }

    public static function getPid($id) {
        return self::where('id', $id)->value('pid');
    }

    public static function state($id, $status) {
        return self::where('id', $id)->update(['status' => $status]);
    }
}
